//
//  ComposeViewController.swift
//  WeiBo_Private
//
//  Created by Yangperlove on 16/1/21.
//  Copyright © 2016年 Yangperlove. All rights reserved.
//

import UIKit
import SVProgressHUD
import SnapKit

class ComposeViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.whiteColor()
        // Do any additional setup after loading the view.
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "toolBarChangeFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
        
        setupNavBar()
        
        setupTextView()
        
        setupToolBar()
        
        setupPicSelectorVControl()
    }
    
    //MARK:toolBar跟随键盘一起移动
    func toolBarChangeFrame(nofification: NSNotification) {
        let duration = (nofification.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
        var offsetY = (nofification.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue().origin.y

        offsetY = -screenSize.height + offsetY
        
        UIView.animateWithDuration(duration) { () -> Void in
            self.toolBar.snp_updateConstraints { (make) -> Void in
                make.bottom.equalTo(self.view.snp_bottom).offset(offsetY)
            }
            self.view.layoutIfNeeded()
        }
        
    }
    
    //MARK:设置ToolBar
    func setupToolBar() {
        self.view.addSubview(toolBar)
        //设置约束
        toolBar.snp_makeConstraints { (make) -> Void in
            make.bottom.left.right.equalTo(self.view)
        }
        
      
        view.addSubview(toolBar)
        toolBar.snp_makeConstraints { (make) -> Void in
            make.bottom.left.bottom.equalTo(view)
        }
        toolBar.backgroundColor = UIColor.randomColor()
        var items = [UIBarButtonItem]()
        let itemSettings = [["imageName": "compose_toolbar_picture", "actionName": "pictrueSelector"],
            ["imageName": "compose_mentionbutton_background"],
            ["imageName": "compose_trendbutton_background"],
            ["imageName": "compose_emoticonbutton_background", "actionName": "selectEmoticon"],
            ["imageName": "compose_add_background"]]
        
        for itemSet in itemSettings {
            let item: UIBarButtonItem
            var image = UIImage(named: itemSet["imageName"]!)
            image = image!.imageWithRenderingMode(.AlwaysOriginal)
            
            if itemSet["actionName"] != nil {
                item = UIBarButtonItem(image: image, style: .Plain, target: self, action:Selector(itemSet["actionName"]!))
            } else {
                item = UIBarButtonItem(image: image, style: .Plain, target: self, action: nil)
            }
            let flexible = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: self, action: nil)
            items.append(item)
            items.append(flexible)
        }
        items.removeLast()
        
        toolBar.items = items

        //添加  toolBar 默认会有高度 44
        
        /*
        //设置toolbar子视图
        var items = [UIBarButtonItem]()
        
        let itemSettings = [["imageName": "compose_toolbar_picture", "actionName": "pictrueSelector"],
            ["imageName": "compose_mentionbutton_background"],
            ["imageName": "compose_trendbutton_background"],
            ["imageName": "compose_emoticonbutton_background", "actionName": "selectEmoticon"],
            ["imageName": "compose_add_background"]]
        
        for item in itemSettings {
            
            //获取图片名称
            let imageName = item["imageName"]
            let btn = UIButton(backImageName: nil, stretchable: false, imageName: imageName, title: nil, fontSize: 17, titleColor: nil)
            if item["actionName"] != nil {
                btn.addTarget(self, action: Selector(item["actionName"]!), forControlEvents: .TouchUpInside)
            }
            let itemBtn = UIBarButtonItem(customView: btn)
            //添加到数组中
            items.append(itemBtn)
            
            //添加弹簧
            let space = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil)
            items.append(space)
           

        }
        //移除最后一个
        items.removeLast()
        //设置视图视图
        toolBar.items = items
    */
    }
    
    //点击图片按钮
    func pictrueSelector() {
        let nav = UINavigationController(rootViewController: PictureSelectorViewController())
        self.presentViewController(nav, animated: true, completion: nil)
        pictureSelectorVControl.view.subviews.first?.hidden = true
    }
    
    //点击表情按钮
    func selectEmoticon() {
        textView.resignFirstResponder()
        textView.inputView = textView.inputView == nil ? emoticonKeyboardView : nil
        textView.becomeFirstResponder()
    }
    
    //MARK:设置发布微博页面View
    func setupTextView() {
        view.addSubview(textView)
        textView.addSubview(placeHolderLabel)
        
        textView.backgroundColor = UIColor.randomColor()
        textView.font = UIFont.systemFontOfSize(17)
        textView.textColor = UIColor.darkGrayColor()
        textView.delegate = self
        textView.alwaysBounceVertical = true
        textView.keyboardDismissMode = .OnDrag
        
        placeHolderLabel.text = "请在此输入"
        placeHolderLabel.textColor = UIColor(white: 0.6, alpha: 1)
        placeHolderLabel.font = UIFont.systemFontOfSize(17)
        
        textView.snp_makeConstraints { (make) -> Void in
            make.top.left.right.equalTo(view)
            make.height.equalTo(screenSize.height * 0.4)
        }
        
        placeHolderLabel.snp_makeConstraints { (make) -> Void in
            make.left.equalTo(textView).offset(6)
            make.top.equalTo(textView).offset(8)
        }
    }

    //MARK:设置导航条
    func setupNavBar() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: .Plain, target: self, action: "send")
        
        navigationItem.rightBarButtonItem?.enabled = false
        
        let titleLabel = UILabel(color: UIColor.randomColor(), fontSize: 17)
        let nameLabel = UILabel(color: UIColor.randomColor(), fontSize: 15)
        composeTitleView.addSubview(titleLabel)
        titleLabel.text = "发布微博"
        composeTitleView.addSubview(nameLabel)
        nameLabel.text = UserAccountViewModel().userName
        
        titleLabel.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(composeTitleView)
            make.top.equalTo(composeTitleView)
        }
        nameLabel.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(composeTitleView)
            make.bottom.equalTo(composeTitleView)
        }
        
        navigationItem.titleView = composeTitleView
    }
    
    //设置图片选择器
    func setupPicSelectorVControl() {
        addChildViewController(pictureSelectorVControl)
        view.addSubview(pictureSelectorVControl.view)
        
        view.bringSubviewToFront(toolBar)
        
        pictureSelectorVControl.view.subviews.first?.hidden = true
        
        pictureSelectorVControl.view.snp_makeConstraints { (make) -> Void in
            make.left.right.bottom.equalTo(self.view)
            make.top.equalTo(textView.snp_bottom)
        }
    }
    
    //点击发送按钮
    func send() {
        var urlString = "https://api.weibo.com/2/statuses/update.json"
        let parameters = ["access_token": UserAccountViewModel().access_token ?? "", "status": textView.fullText() ?? ""]
        if pictureSelectorVControl.imageList.count == 0 {
        NetworkTools.shareTools.networkRequest(HTTPMethod.POST, urlString: urlString, parameters: parameters) { (dict, error) -> () in
            if error != nil {
                SVProgressHUD.showErrorWithStatus("发布微博失败")
                return
            }
            SVProgressHUD.showSuccessWithStatus("发布微博成功")
            NSNotificationCenter.defaultCenter().postNotificationName(ComposeViewControl, object: nil)
        }
        } else {
            urlString = "https://upload.api.weibo.com/2/statuses/upload.json"
            let imageData = UIImagePNGRepresentation(pictureSelectorVControl.imageList.first!)
            
            NetworkTools.shareTools.POST(urlString, parameters: parameters, constructingBodyWithBlock: { (formData) -> Void in
                //将要上传的二进制的文件数据 拼接到 fromData中
                //data: 要上传的文件的二进制数据
                //name: 服务器接受的字段
                //fileName: 服务器存储的文件名  但是在这个地方 可以 '乱写' 自动生成 高清/中等/缩略图
                //mineType: 告诉服务器上传的文件类型
                //图片: image/jpeg  不关注文件类型可以使用:application/octet-stream(八进制的流)
                
                formData.appendPartWithFileData(imageData!, name: "pic", fileName: "x0", mimeType: "image/jpeg")
                
                }, progress: { (progress) -> Void in
                    print(progress)
                }, success: { (_, success) -> Void in
//                    print(success)
                    SVProgressHUD.showSuccessWithStatus("发布微博成功")
                    NSNotificationCenter.defaultCenter().postNotificationName(ComposeViewControl, object: nil)
                    
                }, failure: { (_, error) -> Void in
                    print(error)
                    SVProgressHUD.showErrorWithStatus("发布图片微博失败")
            })
        }
    }
    
    
    func close() {
        dismissViewControllerAnimated(false, completion: nil)
        self.view.layoutIfNeeded()
    }
    
    //MARK:懒加载子控件
    lazy var composeTitleView: UIView = {
        let v = UIView()
        v.frame = CGRect(x: 0, y: 0, width: 200, height: 40)
//        v.backgroundColor = UIColor.randomColor()
        return v
    }()
    
//    lazy var emoticonKeyboardView: EmoticonKeyboardView = EmoticonKeyboardView { (em) -> () in
//        self.textView.insertText(em)
//    }
    lazy var emoticonKeyboardView: EmoticonKeyboardView = EmoticonKeyboardView { (em) -> () in
        print(em)
        //在闭包中智能提示 不怎么样  系统键盘存在的时候 输入视图 为 nil
        self.textView.insertEmoticon(em)
        
    }
    lazy var textView: EmoticonTextView = EmoticonTextView()
    lazy var placeHolderLabel: UILabel = UILabel()
    lazy var toolBar: UIToolbar = UIToolbar()
    lazy var pictureSelectorVControl = PictureSelectorViewController()
    
}
//MARK:textView代理方法
extension ComposeViewController: UITextViewDelegate {
    func textViewDidChange(textView: UITextView) {
        placeHolderLabel.hidden = textView.hasText()
        
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }
}

